<?php

namespace Client;

use Grpc\HelloReq;
use Grpc\HelloRes;
use Hyperf\Context\ApplicationContext;
use Hyperf\Di\Container;
use Hyperf\GrpcClient\BaseClient;
use Psr\SimpleCache\CacheInterface;

use function Hyperf\Config\config;

class GrpcClient extends BaseClient
{
  private static $instance = null;

  public static function instance(): self
  {
    if (!self::$instance) {
      $server_host = config('config.remote.grpc.server_host');
      if (!$server_host) {
        throw new \Exception('grpc server host is empty');
      }

      self::$instance = new self($server_host, ['credentials' => null]);
    }

    $key = config('config.remote.grpc.client_call_times_cache_key');

    /**
     * 记录客户端调用次数
     * @var CacheInterface $cache
     * @var Container $container
     */
    $cache = ApplicationContext::getContainer()->get(CacheInterface::class);
    $time = (int) $cache->get($key, 0);
    $time++;
    $cache->set($key, $time, 3600);

    return self::$instance;
  }

  /**
   * 调用hello
   */
  public function hello(HelloReq $helloReq)
  {
    return $this->_simpleRequest('/grpc.hello/hello', $helloReq, [HelloRes::class, 'decode']);
  }
}
